package com.partvoyage.server.service.authentification;

import java.util.logging.Logger;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.gdata.client.authn.oauth.GoogleOAuthHelper;
import com.google.gdata.client.authn.oauth.GoogleOAuthParameters;
import com.google.gdata.client.authn.oauth.OAuthException;
import com.google.gdata.client.authn.oauth.OAuthHmacSha1Signer;
import com.google.gwt.user.client.rpc.InvocationException;
import com.partvoyage.client.service.login.OAuthService;
import com.partvoyage.client.service.login.exception.NoAccessException;
import com.partvoyage.client.service.login.exception.UserNotLoggedException;
import com.partvoyage.server.servlet.SCMRemoteServiceServlet;
import com.partvoyage.server.utils.Configuration;
import com.partvoyage.shared.ClientConstants;
import com.partvoyage.shared.model.AccessToken;

/**
 * Appelle à google data api avec Oauth
 * 
 * voir pour l'exemple http://code.google.com/p/simple-calendar-manager/
 * 
 * @author ludovic
 * 
 */
public class OAuthServiceImpl extends SCMRemoteServiceServlet implements
		OAuthService {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private final static Logger log = Logger.getLogger(OAuthServiceImpl.class
			.getName());

	private boolean hasAccess(ClientConstants.AppScope scope) {
		return getAccessTokenFromSession(scope.getIdentifier()) != null;
	}

	public void login() throws UserNotLoggedException {
		UserService userService = UserServiceFactory.getUserService();
		if (!userService.isUserLoggedIn()) {
			System.out.println("Demande de login");
			throw new UserNotLoggedException(
					userService.createLoginURL(Configuration.getHomeUrl()));
		}
	}

	public void test() {
		// UTILISER POUR TEST
	}

	@Override
	public User checkAccess(ClientConstants.AppScope scope)
			throws UserNotLoggedException, NoAccessException {
		log.info("checkAccess():: start");

		if (hasAccess(scope)) {
			System.out.println("A acces");
			User currentUserFromSession = getCurrentUserFromSession();
			return currentUserFromSession;
		}

		try {
			// Get the Authorization URL
			System.out.println("Demande d'accès au calendrier");
			String callbackUrl = Configuration.getHomeUrl() + "/oauthAccess"
					+ "?appScope=" + scope.getIdentifier();

			GoogleOAuthParameters oauthParameters = new GoogleOAuthParameters();
			oauthParameters.setOAuthConsumerKey(Configuration
					.getConsumerToken()); // partvoyage.appspot.com
			oauthParameters.setOAuthConsumerSecret(Configuration
					.getConsumerTokenSecret()); // bwOUmNzADbZgyyV7TFGxCBZA
												// peut etre pas bon
			oauthParameters.setOAuthCallback(callbackUrl); // http://127.0.0.1:8888/PartenaireVoyage.html?gwt.codesvr=127.0.0.1:9997/oauthAccess?appScope=calendar
			oauthParameters.setScope(scope.getUrl()); // https://www.google.com/calendar/feeds/

			GoogleOAuthHelper oauthHelper = new GoogleOAuthHelper(
					new OAuthHmacSha1Signer());
			oauthHelper.getUnauthorizedRequestToken(oauthParameters);

			AccessToken accessToken = new AccessToken(
					oauthParameters.getOAuthToken(),
					oauthParameters.getOAuthTokenSecret());
			System.out.println("token retourné : "
					+ accessToken.getOAuthToken() + " et le code secret : "
					+ accessToken.getOAuthTokenSecret());
			setAccessTokenToSession(scope.getIdentifier(), accessToken);

			String authorizationUrl = oauthHelper
					.createUserAuthorizationUrl(oauthParameters);
			System.out.println("autorizationUrl " + authorizationUrl);
			// log.info("checkAccess():: created authorization url");
			throw new NoAccessException(authorizationUrl);
			// }
		} catch (OAuthException oaex) {
			System.out
					.println("probleme lors du log in ou de la demande d'accès "
							+ oaex);
			// log.log(Level.WARNING, "checkAccess()::", oaex);
			throw new InvocationException("", oaex);
		}
	}
}
